package com.pengj.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Controller
public class TestController {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @RequestMapping("/test")
    public String helloWord() {
        System.out.println("访问 login 后台... nowtime = " + LocalDateTime.now().toLocalTime());
        return "test";
    }

    @RequestMapping("/testsession")
    public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
        HttpSession session = request.getSession();
//        session.setAttribute("currentSessionId",session.getId());

        // 1. 设置Session
        /*for (int i = 0; i < 10; i++) {
            String key ="name" + i;
            String value ="session_data_" + i;
            log.info("save data to session ,key={} , value={}",key,value);
            session.setAttribute(key, value);
        }*/
        // 2. 注释第一步,重启tomcat后看是否还可以读取到Session
        String str = "",temp;
        for (int i = 0; i < 10; i++) {
            temp = session.getAttribute("name" + i) + "<br>";
            str = str + temp;
            log.info("read data from session {}",temp);
        }

        System.out.println("测试 redis session ,sid= " + session.getId());
        model.addAttribute("sessionid", session.getId());
        model.addAttribute("str", str);
        return "testsession";
    }
}